/**
 * 在线密码管理平台 - 主要JavaScript文件
 * 子鞍科技股份有限公司
 */

// 全局配置
const AppConfig = {
    apiBaseUrl: '/api',
    defaultPageSize: 25,
    passwordMinLength: 6,
    passwordMaxLength: 32
};

// 工具函数
const Utils = {
    /**
     * 切换密码可见性
     */
    togglePasswordVisibility: function(inputId) {
        const input = document.getElementById(inputId);
        const icon = document.getElementById(inputId + 'Icon');
        
        if (input && icon) {
            if (input.type === 'password') {
                input.type = 'text';
                icon.classList.remove('fa-eye');
                icon.classList.add('fa-eye-slash');
            } else {
                input.type = 'password';
                icon.classList.remove('fa-eye-slash');
                icon.classList.add('fa-eye');
            }
        }
    },


    /**
     * 格式化日期时间
     */
    formatDateTime: function(dateString) {
        if (!dateString) return '-';
        const date = new Date(dateString);
        return date.toLocaleString('zh-CN', {
            year: 'numeric',
            month: '2-digit',
            day: '2-digit',
            hour: '2-digit',
            minute: '2-digit',
            second: '2-digit'
        });
    },

    /**
     * 格式化日期
     */
    formatDate: function(dateString) {
        if (!dateString) return '-';
        const date = new Date(dateString);
        return date.toLocaleDateString('zh-CN');
    },

    /**
     * 复制文本到剪贴板
     */
    copyToClipboard: function(text, callback) {
        if (navigator.clipboard && window.isSecureContext) {
            navigator.clipboard.writeText(text).then(function() {
                if (callback) callback(true);
            }).catch(function(err) {
                console.error('复制失败:', err);
                if (callback) callback(false);
            });
        } else {
            // 降级方案
            const textArea = document.createElement('textarea');
            textArea.value = text;
            textArea.style.position = 'fixed';
            textArea.style.left = '-999999px';
            textArea.style.top = '-999999px';
            document.body.appendChild(textArea);
            textArea.focus();
            textArea.select();
            
            try {
                const successful = document.execCommand('copy');
                if (callback) callback(successful);
            } catch (err) {
                console.error('复制失败:', err);
                if (callback) callback(false);
            } finally {
                document.body.removeChild(textArea);
            }
        }
    },

    /**
     * 显示通知消息
     */
    showNotification: function(message, type = 'info', duration = 3000) {
        const alertClass = `alert-${type}`;
        const iconClass = {
            'success': 'fas fa-check-circle',
            'error': 'fas fa-exclamation-circle',
            'warning': 'fas fa-exclamation-triangle',
            'info': 'fas fa-info-circle'
        }[type] || 'fas fa-info-circle';

        const notification = $(`
            <div class="alert ${alertClass} alert-dismissible fade show position-fixed" 
                 style="top: 20px; right: 20px; z-index: 9999; min-width: 300px;">
                <i class="${iconClass} me-2"></i>
                ${message}
                <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
            </div>
        `);

        $('body').append(notification);

        // 自动消失
        setTimeout(function() {
            notification.alert('close');
        }, duration);
    },

    /**
     * 显示警告框（兼容showAlert）
     */
    showAlert: function(message, type = 'info', duration = 3000) {
        return this.showNotification(message, type, duration);
    },

    /**
     * 验证邮箱格式
     */
    validateEmail: function(email) {
        const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
        return emailRegex.test(email);
    },

    /**
     * 验证手机号格式
     */
    validatePhone: function(phone) {
        const phoneRegex = /^1[3-9]\d{9}$/;
        return phoneRegex.test(phone);
    },

    /**
     * 生成随机字符串
     */
    generateRandomString: function(length = 8) {
        const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
        let result = '';
        for (let i = 0; i < length; i++) {
            result += chars.charAt(Math.floor(Math.random() * chars.length));
        }
        return result;
    },

    /**
     * 防抖函数
     */
    debounce: function(func, wait, immediate) {
        let timeout;
        return function executedFunction(...args) {
            const later = () => {
                timeout = null;
                if (!immediate) func(...args);
            };
            const callNow = immediate && !timeout;
            clearTimeout(timeout);
            timeout = setTimeout(later, wait);
            if (callNow) func(...args);
        };
    },

    /**
     * 节流函数
     */
    throttle: function(func, limit) {
        let inThrottle;
        return function(...args) {
            if (!inThrottle) {
                func.apply(this, args);
                inThrottle = true;
                setTimeout(() => inThrottle = false, limit);
            }
        };
    }
};

// 密码强度检测
const PasswordStrength = {
    /**
     * 检测密码强度
     */
    check: function(password) {
        let score = 0;
        let feedback = [];

        // 长度检查
        if (password.length >= 12) {
            score += 25;
        } else if (password.length >= 8) {
            score += 15;
            feedback.push('建议使用12位以上密码');
        } else {
            score += 5;
            feedback.push('密码长度过短');
        }

        // 字符类型检查
        if (/[a-z]/.test(password)) {
            score += 15;
        } else {
            feedback.push('建议包含小写字母');
        }

        if (/[A-Z]/.test(password)) {
            score += 15;
        } else {
            feedback.push('建议包含大写字母');
        }

        if (/[0-9]/.test(password)) {
            score += 15;
        } else {
            feedback.push('建议包含数字');
        }

        if (/[^a-zA-Z0-9]/.test(password)) {
            score += 30;
        } else {
            feedback.push('建议包含特殊符号');
        }

        // 连续字符检查
        if (!/(.)\1{2,}/.test(password)) {
            score += 10;
        } else {
            feedback.push('避免连续重复字符');
        }

        // 返回结果
        let level, color, text;
        if (score >= 80) {
            level = 'strong';
            color = 'success';
            text = '非常强';
        } else if (score >= 60) {
            level = 'good';
            color = 'info';
            text = '强';
        } else if (score >= 40) {
            level = 'medium';
            color = 'warning';
            text = '中等';
        } else {
            level = 'weak';
            color = 'danger';
            text = '弱';
        }

        return {
            score: score,
            level: level,
            color: color,
            text: text,
            feedback: feedback
        };
    },

    /**
     * 更新密码强度显示
     */
    updateDisplay: function(password, progressElement, textElement) {
        const result = this.check(password);
        
        if (progressElement) {
            progressElement.style.width = result.score + '%';
            progressElement.className = `progress-bar bg-${result.color}`;
        }
        
        if (textElement) {
            textElement.textContent = result.text;
            textElement.className = `text-${result.color}`;
        }
        
        return result;
    }
};

// API 请求封装
const API = {
    /**
     * 发送GET请求
     */
    get: function(url, params = {}) {
        const queryString = new URLSearchParams(params).toString();
        const fullUrl = queryString ? `${url}?${queryString}` : url;
        
        return fetch(fullUrl, {
            method: 'GET',
            headers: {
                'Content-Type': 'application/json',
            },
            credentials: 'same-origin'
        }).then(response => {
            if (!response.ok) {
                throw new Error(`HTTP error! status: ${response.status}`);
            }
            return response.json();
        });
    },

    /**
     * 发送POST请求
     */
    post: function(url, data = {}) {
        return fetch(url, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            credentials: 'same-origin',
            body: JSON.stringify(data)
        }).then(response => {
            if (!response.ok) {
                throw new Error(`HTTP error! status: ${response.status}`);
            }
            return response.json();
        });
    },

    /**
     * 发送表单数据
     */
    postForm: function(url, formData) {
        return fetch(url, {
            method: 'POST',
            credentials: 'same-origin',
            body: formData
        }).then(response => {
            if (!response.ok) {
                throw new Error(`HTTP error! status: ${response.status}`);
            }
            return response.json();
        });
    }
};

// 表单验证
const FormValidator = {
    /**
     * 验证表单
     */
    validate: function(form, rules) {
        const errors = [];
        
        for (const field in rules) {
            const element = form.querySelector(`[name="${field}"]`);
            if (!element) continue;
            
            const value = element.value.trim();
            const fieldRules = rules[field];
            
            // 必填验证
            if (fieldRules.required && !value) {
                errors.push({
                    field: field,
                    message: fieldRules.message || `${field}不能为空`
                });
                this.showFieldError(element, fieldRules.message || `${field}不能为空`);
                continue;
            }
            
            // 长度验证
            if (fieldRules.minLength && value.length < fieldRules.minLength) {
                errors.push({
                    field: field,
                    message: `${field}长度不能少于${fieldRules.minLength}位`
                });
                this.showFieldError(element, `长度不能少于${fieldRules.minLength}位`);
                continue;
            }
            
            if (fieldRules.maxLength && value.length > fieldRules.maxLength) {
                errors.push({
                    field: field,
                    message: `${field}长度不能超过${fieldRules.maxLength}位`
                });
                this.showFieldError(element, `长度不能超过${fieldRules.maxLength}位`);
                continue;
            }
            
            // 格式验证
            if (fieldRules.pattern && !fieldRules.pattern.test(value)) {
                errors.push({
                    field: field,
                    message: fieldRules.patternMessage || `${field}格式不正确`
                });
                this.showFieldError(element, fieldRules.patternMessage || '格式不正确');
                continue;
            }
            
            // 清除错误状态
            this.clearFieldError(element);
        }
        
        return errors;
    },

    /**
     * 显示字段错误
     */
    showFieldError: function(element, message) {
        element.classList.add('is-invalid');
        
        let feedback = element.parentNode.querySelector('.invalid-feedback');
        if (!feedback) {
            feedback = document.createElement('div');
            feedback.className = 'invalid-feedback';
            element.parentNode.appendChild(feedback);
        }
        feedback.textContent = message;
    },

    /**
     * 清除字段错误
     */
    clearFieldError: function(element) {
        element.classList.remove('is-invalid');
        const feedback = element.parentNode.querySelector('.invalid-feedback');
        if (feedback) {
            feedback.remove();
        }
    },

    /**
     * 清除所有错误
     */
    clearAllErrors: function(form) {
        const invalidElements = form.querySelectorAll('.is-invalid');
        invalidElements.forEach(element => {
            this.clearFieldError(element);
        });
    }
};

// 页面加载完成后的初始化
$(document).ready(function() {
    // 初始化工具提示
    const tooltipTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="tooltip"]'));
    tooltipTriggerList.map(function(tooltipTriggerEl) {
        return new bootstrap.Tooltip(tooltipTriggerEl);
    });

    // 初始化弹出框
    const popoverTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="popover"]'));
    popoverTriggerList.map(function(popoverTriggerEl) {
        return new bootstrap.Popover(popoverTriggerEl);
    });

    // 自动隐藏警告框
    $('.alert[data-auto-dismiss]').each(function() {
        const alert = $(this);
        const delay = parseInt(alert.data('auto-dismiss')) || 5000;
        setTimeout(function() {
            alert.alert('close');
        }, delay);
    });

    // 表单自动验证
    $('form[data-validate]').on('submit', function(e) {
        const form = this;
        const rules = JSON.parse(form.dataset.validate || '{}');
        const errors = FormValidator.validate(form, rules);
        
        if (errors.length > 0) {
            e.preventDefault();
            Utils.showNotification('请检查表单输入', 'error');
        }
    });

    // 密码强度实时检测
    $('input[data-password-strength]').on('input', function() {
        const password = this.value;
        const progressSelector = this.dataset.passwordStrength;
        const textSelector = this.dataset.passwordStrengthText;
        
        const progressElement = document.querySelector(progressSelector);
        const textElement = document.querySelector(textSelector);
        
        PasswordStrength.updateDisplay(password, progressElement, textElement);
    });

    // 复制按钮功能
    $(document).on('click', '[data-copy]', function() {
        const text = this.dataset.copy || this.textContent;
        const button = this;
        
        Utils.copyToClipboard(text, function(success) {
            if (success) {
                const originalText = button.innerHTML;
                button.innerHTML = '<i class="fas fa-check"></i> 已复制';
                button.classList.add('btn-success');
                
                setTimeout(function() {
                    button.innerHTML = originalText;
                    button.classList.remove('btn-success');
                }, 2000);
            } else {
                Utils.showNotification('复制失败', 'error');
            }
        });
    });

    // 确认删除对话框
    $(document).on('click', '[data-confirm-delete]', function(e) {
        e.preventDefault();
        const message = this.dataset.confirmDelete || '确定要删除吗？此操作不可恢复。';
        
        if (confirm(message)) {
            // 如果是链接，则跳转
            if (this.tagName === 'A') {
                window.location.href = this.href;
            }
            // 如果是表单按钮，则提交表单
            else if (this.form) {
                this.form.submit();
            }
        }
    });

    // 自动保存功能
    $('[data-auto-save]').on('input', Utils.debounce(function() {
        const element = this;
        const url = element.dataset.autoSave;
        const data = {
            field: element.name,
            value: element.value
        };
        
        API.post(url, data).then(function() {
            Utils.showNotification('已自动保存', 'success', 1000);
        }).catch(function() {
            Utils.showNotification('自动保存失败', 'error', 1000);
        });
    }, 2000));
});

// 导出全局对象
window.App = {
    Utils: Utils,
    PasswordStrength: PasswordStrength,
    API: API,
    FormValidator: FormValidator,
    Config: AppConfig
};